<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学校名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入学校名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学校类别" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择学校类别" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学校性质" prop="nature">
        <el-select v-model="queryParams.nature" placeholder="请选择学校性质" clearable size="small">
          <el-option
            v-for="dict in natureOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="责任人" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入责任人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['patrol:school:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['patrol:school:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['patrol:school:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['patrol:school:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="schoolList" style="color: #333333" :header-cell-style="{background:'#E3E3E3'}">
      <el-table-column label="学校名称" align="center" prop="name"/>
      <el-table-column label="类别" align="center" prop="type" :formatter="typeFormat"/>
      <el-table-column label="性质" align="center" prop="nature" :formatter="natureFormat"/>
      <el-table-column label="责任人员" align="center" prop="sysUser.nickName"/>
      <el-table-column label="责任人电话" align="center" prop="sysUser.phonenumber"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['patrol:school:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['patrol:school:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handleResetPw(scope.row)"
            v-hasPermi="['patrol:school:edit']"
          >重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学校信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body  @close="closeDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="125px">
        <el-form-item label="学校名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入学校名称"/>
        </el-form-item>
        <el-form-item label="学校类别" prop="type">
          <el-select v-model="form.type" placeholder="请选择学校类别">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校性质" prop="nature">
          <el-select v-model="form.nature" placeholder="请选择学校性质">
            <el-option
              v-for="dict in natureOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="责任人" prop="sysUser.nickName">
          <el-input v-model="form.sysUser.nickName" placeholder="请输入责任人姓名"/>
        </el-form-item>
        <el-form-item label="责任人电话" prop="sysUser.phonenumber">
          <el-input v-model="form.sysUser.phonenumber" placeholder="请输入责任人电话"/>
        </el-form-item>
        <el-form-item label="紧急联系人" prop="urgent">
          <el-input v-model="form.urgent" placeholder="请输入紧急联系人"/>
        </el-form-item>
        <el-form-item label="紧急联系人电话" prop="urgentPhone">
          <el-input v-model="form.urgentPhone" placeholder="请输入紧急联系人电话"/>
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <div class="el-upload__tip" style="margin-left: 20px;">注意：学校管理员添加成功后，只可登录网页端</div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改学校信息对话框 -->
    <el-dialog title="重置管理员密码" :visible.sync="openPwd" width="500px" append-to-body>
      <el-form ref="formPwd" :model="formPwd" :rules="rulesPwd" label-width="100px">
        <el-form-item label="责任人员" prop="nickName">
          <el-input v-model="formPwd.nickName" disabled/>
        </el-form-item>
        <el-form-item label="重置密码" prop="password">
          <el-input v-model="formPwd.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="passwordRepeat">
          <el-input v-model="formPwd.passwordRepeat" type="password" placeholder="请确认密码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPwd">取 消</el-button>
        <el-button type="primary" @click="submitFormPwd">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listSchool, getSchool, delSchool, addSchool, updateSchool, exportSchool} from "@/api/patrol/school";
import {resetSchoolPwd} from "@/api/system/user";

export default {
  name: "School",
  data() {
    let pwdStrength = (pwd) => {
      let strength = 0;
      if (pwd.length >= 12) strength += 1;
      if (pwd.match(/[A-Z]/)) strength += 1;
      if (pwd.match(/[a-z]/)) strength += 1;
      if (pwd.match(/[0-9]/)) strength += 1;
      if (pwd.match(/[\W_]/)) strength += 1;
      return strength
    };
    let validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空'));
      } else if (pwdStrength(value) < 5) {
        callback(new Error('密码必须包含大小写字母、数字和符号'));
      } else if (value !== this.formPwd.passwordRepeat) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    let validatePasswordRepeat = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('确认密码不能为空'));
      } else if (value !== this.formPwd.password) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学校信息表格数据
      schoolList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（重置密码）
      openPwd: false,
      // 学校类别字典
      typeOptions: [],
      // 学校性质字典
      natureOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        nature: null,
        nickName: null,
      },
      // 表单参数
      form: {sysUser: {}},
      // 表单参数(重置密码)
      formPwd: {
        id: null,
        nickName: null,
        password: null,
        passwordRepeat: null,
      },
      // 表单校验
      rules: {
        name: [
          {required: true, message: "学校名称不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "学校类别不能为空", trigger: "change"}
        ],
        nature: [
          {required: true, message: "学校性质不能为空", trigger: "change"}
        ],
        sysUser: {
          nickName: [
            {required: true, message: "学校责任人不能为空", trigger: "change"}
          ],
          phonenumber: [
            {required: true, message: "学校责任人电话不能为空", trigger: "change"},
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ],
        },
        urgent: [
          {required: true, message: "紧急联系人不能为空", trigger: "blur"}
        ],
        urgentPhone: [
          {required: true, message: "紧急联系人电话不能为空", trigger: "blur"},
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
      },
      // 表单校验（重置密码）
      rulesPwd: {
        password: [
          {required: true, message: "密码不能为空", trigger: "blur"},
          { min: 12, max: 20, message: "长度在 12 到 20 个字符", trigger: "blur" },
          {validator: validatePassword, trigger: 'change'}
        ],
        passwordRepeat: [
          {required: true, message: "确认密码不能为空", trigger: "blur"},
          {validator: validatePasswordRepeat, trigger: 'change', required: true}
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("shool_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("school_nature").then(response => {
      this.natureOptions = response.data;
    });
  },
  methods: {
    /** 查询学校信息列表 */
    getList() {
      this.loading = true;
      listSchool(this.queryParams).then(response => {
        this.schoolList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 学校类别字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 学校性质字典翻译
    natureFormat(row, column) {
      return this.selectDictLabel(this.natureOptions, row.nature);
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.open = false;
    },
    // 取消按钮（重置密码）
    cancelPwd() {
      this.resetPwdForm();
      this.openPwd = false;
    },
    closeDialog() {
      this.reset();
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        nature: null,
        sysUser: {
          phonenumber: null,
          nickName: null
        },
      };
      this.resetForm("form");
    },
    // 表单重置（重置密码）
    resetPwdForm() {
      this.formPwd = {
        id: null,
        nickName: null,
        password: null,
        passwordRepeat: null,
      };
      this.resetForm("formPwd");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学校信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      getSchool(row.id).then(response => {
        this.open = true;
        this.title = "修改学校信息";
        this.form = response.data;
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSchool(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSchool(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.resetQuery();
            });
          }
        }
      });
    },
    /** 提交按钮（重置密码） */
    submitFormPwd() {
      this.$refs["formPwd"].validate(valid => {
        if (valid) {
          resetSchoolPwd(this.formPwd.id, this.formPwd.password).then(response => {
            this.msgSuccess("密码修改成功");
            this.openPwd = false;
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除所选数据?', "警告", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        closeOnClickModal: false,
        type: "warning"
      }).then(function () {
        return delSchool(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 重置密码操作 */
    handleResetPw(row) {
      this.resetPwdForm();
      this.formPwd.id = row.id;
      this.formPwd.nickName = row.sysUser.nickName;
      this.openPwd = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有学校信息数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      }).then(function () {
        return exportSchool(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
  }
};
</script>
